<template>
  <Map class="map"></Map>
  <div class="tool" v-if="isTool">
    框选数据：
    <el-button type="primary" @click="draw('rectangle')">矩形</el-button>
    <el-button type="primary" @click="draw('polygon')">面</el-button>
    <el-button type="primary" @click="draw('circle')">圆</el-button>
    <el-button type="primary" @click="measureArea">水平面积</el-button>
    <el-button type="danger" @click="removeAll">清除</el-button>
  </div>
  <Pop
    modal-class="inspeactTaskModal"
    class="inspeactTaskPop"
    ref="popRef"
    title="新增任务"
    width="704px"
    @confirm="confirm"
    :modal="false"
    ><template #header>
      <div class="pop_header">新增任务</div>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="selectRange">修改范围</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </span>
    </template>
    <ComForm ref="editFormRef" :format="editFormat" @selectRange="selectRange">
      <template #popInfo>
        <div class="box">
          <li>管线长度：{{ pipelineLength }}</li>
          <li>管点(个):{{ pipePoint }}</li>
          <li>管线(条):{{ pipeline }}</li>
        </div>
      </template>
    </ComForm>
  </Pop>
</template>
<script setup >
import { computed, onMounted, ref } from "vue";
import { map } from "@/utils/map.ts";
import useAppStore from "@/store/modules/app";
import * as mars3d from "mars3d";
import { getRangePipeInfo, addPatrolTask } from "@/api/task/task";
import { transformCar } from "@/utils/Lmap";

const { proxy } = getCurrentInstance();
const points = ref({});
let graphicLayer;
let measure;
const pipelineLength = ref(null);
const pipePoint = ref(null);
const pipeline = ref(null);
//被选中的图层
let selectGraphic = [];
const removeAll = () => {
  map.graphicLayer.clear();

  for (let i = 0; i < selectGraphic.length; i++) {
    const graphic = selectGraphic[i];
    graphic.setStyle({
      image:
        "https://img.tukuppt.com/ad_preview/00/05/77/QjdeODlmsB.jpg!/fw/260",
    });
  }
  selectGraphic = [];
};
//画
const draw = async (type) => {
  const graphic = await map.graphicLayer
    .startDraw({
      type: type,
      style: {
        color: "#ffff00",
        opacity: 0.2,
        clampToGround: true, //是否贴地
        outline: true,
        outlineColor: "#fafa5a",
        outlineWidth: 1,
      },
    })
    .then(async (graphic) => {
      console.log("绘制矢量对象完成", graphic);
      points.value = transformCar(graphic._positions_draw);
      const res = await getRangePipeInfo(
        JSON.stringify(transformCar(graphic._positions_draw))
      );
      const { lineNumber, pipeLength, pointNumber } = res.data;
      pipelineLength.value = pipeLength;
      pipeline.value = lineNumber;
      pipePoint.value = pointNumber;
      popRef.value.show();
      editFormRef.value.changeForm({
        info: `管线长度:${pipelineLength.value}\n管点(个):${pipePoint.value}\n管线（条）:${pipeline.value}`,
      });
    });
  updateSelect(graphic);
};

// 在范围内的改变图标为红色
const updateSelect = (drawGraphic) => {
  graphicLayer.eachGraphic((graphic) => {
    const position = graphic.positionShow;

    const isInArea = drawGraphic.isInPoly(position);
    if (isInArea) {
      graphic.setStyle({
        image:
          "https://img.tukuppt.com/ad_preview/00/05/77/QjdeODlmsB.jpg!/fw/260",
      });
      selectGraphic.push(graphic);
    }
  });
};

// 水平面积
const measureArea = async () => {
  const graphic2 = await measure
    .area({
      style: {
        color: "#00fff2",
        opacity: 0.4,
        outline: true,
        outlineColor: "#fafa5a",
        outlineWidth: 1,
        clampToGround: false, //贴地
      },
    })
    .then((graphic) => {
      console.log(graphic);
    });
};

console.log(2222, "页面中", map);
const isTool = ref(false);
const store = useAppStore();
const popRef = ref();
const editFormRef = ref();
const confirm = () => {
  editFormRef.value.checkForm().then(async (result) => {
    if (result) {
      //内部执行提交逻辑
      const res = await addPatrolTask(
        JSON.stringify({
          ...editFormRef.value.getFormItem(),
          points: points.value,
        })
      );
      if (res.code == 200) {
        pipelineLength.value = null;
        pipePoint.value = null;
        pipeline.value = null;
        proxy.$modal.msgSuccess(res.msg);
        editFormRef.value.reset();
        popRef.value.hide();
      }
    }
  });
};
// 编辑表单配置
const editFormat = ref([
  {
    label: "任务名称",
    prop: "taskName",
    type: "input",
    span: 24,
    rules: [
      {
        required: true,
        message: "输入任务名称",
        trigger: "blur",
      },
    ],
  },
  {
    label: "巡检人",
    prop: "patrolPerson",
    type: "input",
    span: 12,
    rules: [
      {
        required: true,
        message: "请输入巡检人",
        trigger: "blur",
      },
    ],
  },
  {
    label: "任务区域",
    prop: "patrolArea",
    type: "input",
    span: 12,
    rules: [
      {
        required: true,
        message: "请输入任务区域",
        trigger: "blur",
      },
    ],
  },
  {
    label: "查询时间",
    prop: "patrolTime",
    type: "date",
    span: 12,
    rules: [
      {
        required: true,
        message: "请输入查询时间",
        trigger: "blur",
      },
    ],
  },
  {
    label: "巡检方式",
    prop: "patrolWay",
    type: "select",
    rules: [
      {
        required: true,
        message: "请选择巡检方式",
        trigger: "blur",
      },
    ],
    option: [
      { label: "人工巡查", value: 1 },
      { label: "车辆巡检", value: 2 },
      { label: "人工与车辆结合", value: 3 },
    ],
    span: 12,
  },
  {
    label: "备注",
    prop: "remark",
    type: "input",
    span: 24,
  },
  // {
  //   slotName: "popInfo",
  //   type: "slot",
  //   span: 24,
  // },
  {
    label: "范围信息",
    prop: "info",
    type: "textarea",
    disabled: true,
    show: () => (pipelineLength.value == null ? false : true),
    defaultValue: computed(
      () =>
        `管线长度:${pipelineLength.value}\n管点(个):${pipePoint.value}\n管线（条）:${pipeline.value}`
    ),
    span: 24,
  },
  // {
  //   label: "",
  //   prop: "xxx",
  //   type: "button",
  //   btns: [
  //     {
  //       label: computed(() =>
  //         pipelineLength.value == null ? "选取范围" : "修改范围"
  //       ),
  //       event: "selectRange",
  //       type: "success",
  //     },
  //   ],
  //   span: 24,
  // },
]);

const selectRange = () => {
  popRef.value.hide();
  isTool.value = true;
};
const sideClick = (data) => {
  console.log(data);
  if (data.index == "/mission/inspectTask/inspeactTaskAdd") popRef.value.show();
};
store.changeSide(sideClick);
onMounted(() => {
  popRef.value.show();
  console.log(2222, "页面中", map);
  measure = new mars3d.thing.Measure();
  // 创建矢量数据图层
  graphicLayer = new mars3d.layer.GraphicLayer({
    isAutoEditing: true, // 绘制完成后是否自动激活编辑
    hasEdit: true,
  });

  measure.on(mars3d.EventType.change, function (event) {
    console.log("发送了变化", event);
  });
  map.addLayer(graphicLayer);
  map.addThing(measure);
});
</script>
<style >
.inspeactTaskPop {
  top: 50% !important;
  transform: translateY(-60%);
  pointer-events: all !important;
}
.inspeactTaskModal {
  pointer-events: none !important;
}
</style>
<style scoped>
.tool {
  top: 20px;
  right: 10%;
  z-index: 10;
  position: absolute;
  pointer-events: all;
  background-color: #2e333d;
  color: #fff;
  padding: 20px 20px;
  border: 1px solid #fff;
  border-radius: 8px;
}
.box {
  background-color: #fff;
  padding: 30px;
  list-style: none;
}
.pop_header {
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: MiSans;
  font-weight: 500;
  font-size: 18px;
  color: #0f0f0f;
  line-height: 23px;
  background: #ffffff;
  /* border-bottom: 1px solid #d2d5dc; */
}
</style>